# coding: utf8
"""
RPA邮件工具
"""
import datetime
import os.path

import dateutil.parser
from independentsoft.msg import (Attachment, DisplayType, Message, MessageFlag,
                                 ObjectType,
                                 Recipient, RecipientType, StoreSupportMask)


def saveToMsg(isrpaMailMessage, dirPath: str = ".", fileName: str = "",
              encoding="gb2312") -> str:
    """
    保存艺赛旗RPA的MailMessage对象为.msg文件

    参考方法，independentsoft.msg（需要pip install independentsoft.msg）：
    https://pypi.org/project/independentsoft.msg/

    如果想保存为.eml文件，可以参考此链接
    https://github.com/JoshData/convert-outlook-msg-file

    :param isrpaMailMessage: 艺赛旗RPA的MailMessage，【xx接收邮件】组件返回值列表中的元素
        MailMessage属性: subject, sender, received_time, body, cc, attachments
    :param dirPath: .msg文件保存目录
    :param fileName: .msg文件名称
    :param encoding: 邮件内容编码，默认中文，支持utf-8等（可能会乱码）
    :return:
    """
    from ubpa.iresult import MailMessage
    if not isinstance(isrpaMailMessage, MailMessage):
        raise ValueError("isrpaMailMessage参数不接受非艺赛旗MailMessage对象")

    if not isinstance(fileName, str):
        raise ValueError("保存结果.msg文件的fileName参数需要str")

    if isinstance(isrpaMailMessage.received_time, str):
        try:
            isrpaMailMessage.received_time = dateutil.parser.parse(
                isrpaMailMessage.received_time).replace(tzinfo=None)
        except:
            pass

    received_time = str(isrpaMailMessage.received_time)
    if isinstance(isrpaMailMessage.received_time, datetime.datetime):
        received_time = isrpaMailMessage.received_time.strftime("%Y%m%d_%H%M%S")

    # 替换Windows文件名中的非法字符为下划线
    rstr = r"[\/\\\:\*\?\"\<\>\|]"  # '/ \ : * ? " < > |'
    subject_title = re.sub(rstr, "_", str(isrpaMailMessage.subject))
    subject_title = subject_title.replace(" ", "")
    if not fileName:
        fileName = f"{subject_title}_{received_time}"
    msgFile = f"{fileName}.msg"
    msgPath = os.path.abspath(os.path.join(dirPath, msgFile))

    # # 组装邮件
    message = Message()
    message.encoding = encoding
    message.subject = isrpaMailMessage.subject  # 主题
    message.body = isrpaMailMessage.body  # 正文

    # 富文本内容，根据邮件内容格式进行改造判断
    # try:
    #     _body = isrpaMailMessage.body.encode("gb2312")
    #     message.body_html_text = isrpaMailMessage.body
    #     message.body_rtf = _body
    #
    #     # html_body = f"<html><body>{isrpaMailMessage.body}</body></html>"
    #     # html_body_with_rtf = "{\\rtf1\\ansi\\ansicpg1252\\fromhtml1 \\htmlrtf0 " + html_body + "}"
    #     # rtf_body = html_body_with_rtf.encode("utf_8")
    #     # message.body_html_text = html_body
    #     # message.body_rtf = rtf_body
    # except:
    #     pass

    # 时间
    message.client_submit_time = isrpaMailMessage.received_time

    # 发件
    sender = Recipient()
    sender.display_type = DisplayType.MAIL_USER
    sender.object_type = ObjectType.MAIL_USER
    sender.display_name = isrpaMailMessage.sender
    sender.email_address = isrpaMailMessage.sender
    sender.recipient_type = RecipientType.TO
    message.recipients.append(sender)

    # 抄送
    for cc in isrpaMailMessage.cc:
        recipient = Recipient()
        recipient.display_type = DisplayType.MAIL_USER
        recipient.object_type = ObjectType.MAIL_USER
        recipient.display_name = cc
        recipient.email_address = cc
        recipient.recipient_type = RecipientType.CC
        message.recipients.append(recipient)

    # 附件
    for file in isrpaMailMessage.attachments:
        attachment = Attachment(file_path=file)
        message.attachments.append(attachment)

    # 保存
    message.message_flags.append(MessageFlag.UNSENT)
    message.store_support_masks.append(StoreSupportMask.CREATE)
    message.save(msgPath)

    if not os.path.exists(msgPath):
        # 校验，并按接收时间重新保存
        msgPath = os.path.abspath(os.path.join(dirPath, f"{received_time}.msg"))
        message.save(msgPath)
    return msgPath


def batchSaveToMsg(isrpaMailMessages: list, dirPath: str = ".") -> list:
    """
    批量保存艺赛旗RPA的MailMessage对象为.msg文件

    具体使用方法（需求场景）查看艺赛旗社区贴，链接地址：
    https://support.i-search.com.cn/article/1681961182315

    :param isrpaMailMessages: 艺赛旗RPA的MailMessage对象列表，【xx接收邮件】组件返回值
    :param dirPath: .msg文件保存目录
    :return:
    """
    msgPathList = [saveToMsg(imm, dirPath) for imm in isrpaMailMessages]
    return msgPathList
